﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Web.Caching;
using PAMD.Database.Model;
using System.Data.Objects;

namespace PAMD.Database.Services
{
    [Export(typeof(CommonService))]
    [PartCreationPolicy(CreationPolicy.Shared)]
    public class CommonService
    {
        readonly PAMDEntities _contexts = new PAMDEntities();

        public CommonService()
        {
            _contexts.ListingFeatures.MergeOption = MergeOption.OverwriteChanges;
            _contexts.ListingPhotoes.MergeOption = MergeOption.OverwriteChanges;
            _contexts.ListingPrices.MergeOption = MergeOption.OverwriteChanges;
            _contexts.Listings.MergeOption = MergeOption.OverwriteChanges;
            _contexts.Occupations.MergeOption = MergeOption.OverwriteChanges;
            _contexts.Registrations.MergeOption = MergeOption.OverwriteChanges;
            _contexts.UserDetails.MergeOption = MergeOption.OverwriteChanges;
            _contexts.Addresses.MergeOption = MergeOption.OverwriteChanges;
            _contexts.Countries.MergeOption = MergeOption.OverwriteChanges;
        }

        public List<KeyValue> GetCountryList()
        {
            Cache cache = System.Web.HttpContext.Current.Cache;
            var countries = (List<KeyValue>)cache["Countries"];
            if (countries == null)
            {
                countries = _contexts.Countries.ToList().Select(country => new KeyValue { Id = country.ID.ToString(), Text = country.CountryName }).ToList();
                cache["Countries"] = countries;
            }

            return countries;
        }

        public List<KeyValue> GetOccupationList()
        {
            Cache cache = System.Web.HttpContext.Current.Cache;
            var occupations = (List<KeyValue>)cache["OccupationList"];
            if (occupations == null)
            {
                occupations = _contexts.Occupations.ToList().Select(occupation => new KeyValue { Id = occupation.ID.ToString(), Text = occupation.Name }).ToList();
                cache["OccupationList"] = occupations;
            }

            return occupations;
        }
    }
}